import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:small_intestine_cell2/MessageDialog.dart';
import 'package:small_intestine_cell2/UpgradeDialog.dart';


// or new Dio with a BaseOptions instance.
var options = BaseOptions(
  baseUrl: 'http://update.sunvua.com:12321',
  connectTimeout: 5000,
  receiveTimeout: 300000,
);

Dio getDio() {
  return Dio(options);
}

class Upgrade {
  var upgradeProgress;
  late StateSetter upgradeState;
  late BuildContext context;
  late FToast fToast;
  void upGradeRequest(profileName, packageName,version,showPoint) async {
    fToast = FToast();
    fToast.init(context);
    final queryParameters = <String, dynamic>{
      r'n': profileName,
      r'm': kReleaseMode ? "release" : "debug"
    };

    var response = await getDio()
        .get("/app/version", queryParameters: queryParameters)
        .catchError((e) {});
    // var result = response.data.toString();
    // Map<String, dynamic> map = jsonDecode(result);

    var data = response.data["data"];
    // response.data;
    // _showUpgradeDialog("packageName", {"versionName":"1.92.3"});
    if(version<data["versionCode"]){
    _showUpgradeDialog("packageName", data, profileName);
    }else{
      if(showPoint){
        _showToast("当前已是最新版本!");
      }
    }
  }

  void _showUpgradeDialog(packageName, data, profileName) {
    showDialog(
        context: context!,
        builder: (context) {
          return MessageDialog(
              "版本更新", Text("检测到有新版本(v${data["versionName"]}), 是否立即更新?"), () {
                () async {
              var hasPermission = false;

              while (!hasPermission) {
                PermissionStatus status = await Permission.storage.status;
                if (status != PermissionStatus.granted) {
                  status = await Permission.location.request();
                }
                hasPermission = (status == PermissionStatus.granted);
              }
              var downurl =
                  "${options.baseUrl}/files/$profileName-${data["versionName"]}-${data["versionCode"]}-${kReleaseMode ? "release" : "debug"}.apk";
              _executeUpgrade(packageName, data["versionName"], downurl);
            }.call();
          }, cancel: () {
            if (data["force"] ?? true) {
              SystemNavigator.pop();
            }
          }, submitText: "立即更新");
        });
  }

  void _executeUpgrade(packageName, versionName, url) async {
    var local = await getPhoneLocalPath();
    var path =
        "$local$packageName/upload/${packageName}_$versionName${new DateTime.now().microsecondsSinceEpoch}.apk";

    var exist = await File(path).exists();
    if (exist) {
      await OpenFile.open(path);
      SystemNavigator.pop();
    } else {

      upgradeProgress = ["0"];
      showDialog(
          context: context,
          builder: (context) {
            return StatefulBuilder(
              builder: (ctx, state) {
                upgradeState = state;
                return UpgradeDialog(upgradeProgress);
              },
            );
          });
      getDio().download(url, path, onReceiveProgress: (received, total) async {
        if (total == -1) {
          _showToast("安装包数据异常,请联系管理员!");
          Navigator.pop(context);
        } else if (total != received) {
          upgradeState(() {
            upgradeProgress[0] = (received / total * 100).toStringAsFixed(0);
          });
        } else {
          Navigator.pop(context);
          await OpenFile.open(path);
          SystemNavigator.pop();
        }
      }).catchError((e) {
        _showToast("服务器异常,请联系管理员!");
        Navigator.pop(context);
      });
    }
  }

  Future<String> getPhoneLocalPath() async {
    final directory = Theme.of(context).platform == TargetPlatform.android
        ? await getApplicationDocumentsDirectory()
        : await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Upgrade(this.context);

  _showToast(text) {
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.greenAccent,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Icon(Icons.check),
          SizedBox(
            width: 12.0,
          ),
          Text("$text"),
        ],
      ),
    );


    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: Duration(seconds: 2),
    );
    //
    // // Custom Toast Position
    // fToast.showToast(
    //     child: toast,
    //     toastDuration: Duration(seconds: 2),
    //     positionedToastBuilder: (context, child) {
    //       return Positioned(
    //         child: child,
    //         top: 16.0,
    //         left: 16.0,
    //       );
    //     });
  }

}
